package com.sfx.shortLink.mq.idempotent;


import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 消息幂等处理器
 */
@Component
@RequiredArgsConstructor
public class MessageIdempotentHandler {

    private final StringRedisTemplate stringRedisTemplate;
    private static final String IDEMPOTENT_KEY_PREFIX = "short-link:idempotent:";


    /**
     * 判断消息是否正在消费
     *
     * @param messageId 消息id
     * @return 返回是否正在消费
     */
    public boolean isConsume(String messageId) {
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(IDEMPOTENT_KEY_PREFIX + messageId, "0", 3, TimeUnit.MINUTES));
    }

    /**
     * 设置消息已经为消费完成状态
     *
     * @param messageId 消息id
     */
    public void setAccomplish(String messageId) {
        stringRedisTemplate.opsForValue().set(IDEMPOTENT_KEY_PREFIX + messageId, "1", 3, TimeUnit.MINUTES);
    }

    /**
     * @param messageId 消息id
     * @return 返回消息是否已经消费完成
     */
    public boolean isAccomplish(String messageId) {
        return Objects.equals(stringRedisTemplate.opsForValue().get(IDEMPOTENT_KEY_PREFIX + messageId), "1");
    }

    /**
     * 删除消息
     *
     * @param messageId 消息id
     */
    public void delMessage(String messageId) {
        stringRedisTemplate.delete(IDEMPOTENT_KEY_PREFIX + messageId);
    }
}